package com.isoft.c2team3service2.service.impl;

import com.isoft.c2team3service2.service.EmailService;
import com.isoft.c2team3service2.util.RedisConstants;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

import static com.isoft.c2team3service2.util.RedisConstants.USER_CODE_KEY;
import static com.isoft.c2team3service2.util.RedisConstants.USER_CODE_TTL;

@Service
@RequiredArgsConstructor
public class EmailServiceImp implements EmailService {
    private static final Logger log = LoggerFactory.getLogger(EmailServiceImp.class);
    
    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void sendVerificationCode(String email) {
        // 1. 生成6位纯数字验证码
        String code = String.format("%06d", new Random().nextInt(999999));
        // 2. 统一处理邮箱：trim去除空格
        String processedEmail = email.trim();
        // 3. 日志打印：记录处理后的邮箱和验证码（便于排查）
        log.info("生成艺人注册验证码：processedEmail={}, code={}", processedEmail, code);
        // 4. 删除旧验证码（避免残留）
        stringRedisTemplate.delete(USER_CODE_KEY + processedEmail);
        // 5. 存储新验证码到Redis（仅一次存储，避免覆盖）
        stringRedisTemplate.opsForValue().set(
                USER_CODE_KEY + processedEmail,
                code,
                USER_CODE_TTL,
                TimeUnit.MINUTES
        );
        // 6. 发送邮件（使用处理前的原邮箱，确保用户能收到）
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("15005923839@163.com");
        message.setTo(email);
        message.setSubject("注册验证码");
        message.setText("您的注册验证码是：" + code + "，有效期" + USER_CODE_TTL + "分钟，请尽快使用。");
        mailSender.send(message);
    }}